//@author A0106044W
package logic;

import java.util.ArrayList;
import java.util.logging.Level;

import commandInfo.AddFilterCommandInfo;
import commandInfo.CommandInfo;
import commandInfo.RemoveFilterCommandInfo;
import storage.Task;

/**
 * 
 * 
 * 	       Sothearith Sreang
 *         All of the Logic part is written by me.
 * 
 */

public class RemoveFilterHandler extends OperationHandler {
	ArrayList<Task> filterTasksList;

	private static final String SUCCESSFUL_DELETE_MESSAGE = "%d task%s now successfully deleted";
	private static final String UNSUCCESSFUL_DELETE_MESSAGE = "task found in displayList cannot be found in storage. Check Storage and Logic who passes this task";
	private static final String SUCCESSFUL_UNDO_MESSAGE = "%d task%s are now successfully added";

	// Two public constructors

	// for normal remove operation
	public RemoveFilterHandler(ArrayList<Task> taskList) {
		super();
		filterTasksList = taskList;
	}

	// for redo, undo operation
	public RemoveFilterHandler(CommandInfo commandInfoP) {
		super();
		setTaskList(commandInfoP);
	}

	// This method is called for user command's filter remove operation
	public String execute() {
		ArrayList<Task> cloneTasksList = new ArrayList<Task>();

		for (Task task : filterTasksList) {
			removeTask(task, cloneTasksList);
		}

		super.commandInfo = new RemoveFilterCommandInfo(cloneTasksList);
		String feedback = Helper.setUpFeedback(SUCCESSFUL_DELETE_MESSAGE,
				filterTasksList.size());

		return feedback;
	}

	// This method is called for undo for previous filter remove operation
	public String undo() {

		for (Task task : filterTasksList) {
			addTask(task);
		}
		
		super.commandInfo = new AddFilterCommandInfo(filterTasksList);
		String feedback = Helper.setUpFeedback(SUCCESSFUL_UNDO_MESSAGE, filterTasksList.size());
		
		return feedback;
	}

	// next level abstraction

	private void setTaskList(CommandInfo commandInfoP) {
		filterTasksList = commandInfoP.getPreviousTasksList();
	}

	private void removeTask(Task task, ArrayList<Task> cloneTasksList) {
		boolean isSuccess = false;

		try {
			isSuccess = storage.removeTask(task);
			Task taskClone = getTaskClone(task);
			
			if (isSuccess) {
				cloneTasksList.add(taskClone);
			} else {
				Logic.logger.log(Level.SEVERE,
						UNSUCCESSFUL_DELETE_MESSAGE);
			}
		} catch (Exception e) {
			Logic.logger.log(Level.SEVERE, e.getMessage());
		}
	}

	private void addTask(Task task) {
		try {
			super.storage.addTask(task);
		} catch (Exception e) {
			Logic.logger.log(Level.SEVERE, "Task is null.");
		}

	}

	private Task getTaskClone(Task task) {
		Task taskClone = null;

		try {
			taskClone = task.cloneSelf();
		} catch (Exception e) {
			Logic.logger.log(Level.SEVERE, e.getMessage());
		}

		return taskClone;
	}
}
